package ia;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import java.util.Scanner;

import utility.Point;
import multiplayer.lan.Move;



public class Engine extends Observable implements Runnable{
	
	private HashMap<String, Integer> number= new HashMap<String, Integer>() ;
	private String[] letter={"a","b","c","d","e","f","g","h"};
	private String line;
	boolean active=true;
	private OutputStream stdin = null;
	private InputStream stdout = null;
	private Process process ;
	
	public Engine() {
		number.put("a", 1);
		number.put("b", 2);
		number.put("c", 3);
		number.put("d", 4);
		number.put("e", 5);
		number.put("f", 6);
		number.put("g", 7);
		number.put("h", 8);
	}
	
	public boolean isActive() {
		return active;
	}
	
	public void setActive(boolean active) {
		this.active = active;
	}

	public void closeProcess(){
		try {
			stdin.close();
			stdout.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			process.destroy();
		}
	}

	public void startEngine() throws IOException{
		process = Runtime.getRuntime ().exec ("chessEngine/gnuchess-5.50-64.exe -x");
		stdin = process.getOutputStream ();
		stdout = process.getInputStream ();
	}


	public void move(String s) throws IOException{
		line = s+"\n";
		stdin.write(line.getBytes() );
		stdin.flush();
	}
	
	public Move parsingStringFromEngine(String s){
		String[] buff=s.split(" ");
		Point from=new Point(8-Integer.parseInt(""+buff[1].charAt(1)), number.get(""+buff[1].charAt(0))-1);
		Point to=new Point(8-Integer.parseInt(""+buff[1].charAt(3)),number.get(""+buff[1].charAt(2))-1);
		return new Move(from, to);
	}
	
	public String parsingMoveforEngine(Move m){
		StringBuilder sb = new StringBuilder();
		Point from = m.getFrom();
		Point to= m.getTo();
		sb.append(letter[from.getY()]+""+(8-from.getX())+""+letter[to.getY()]+""+(8-to.getX()));
		return sb.toString();
	}

	public boolean isMove(String string) {
		String[] splitted = string.split(" ");
		if(splitted.length==2){
			if(splitted[0].equals("move")){
				return true;
			}
		}
		return false;
	}
	
	@Override
	public void run() {
		BufferedReader brCleanUp =new BufferedReader (new InputStreamReader (stdout));
		try {
			while ((line = brCleanUp.readLine ()) != null && active) {
				System.out.println("ricevuto: "+line);
				setChanged();
				notifyObservers(line);
			}
		} catch (IOException e) {
			closeProcess();
			e.printStackTrace();
		}
	}
}
